import React, { Component } from 'react';
import CustomForm from '../../../components/CustomForm';
import { Input, message, Select } from 'antd';
import services from '../../../services/api';
import ScriptEditor from '../../../components/ScriptEditor';
import { connect } from 'react-redux';
import DataTypeDesc from '../../../components/DataTypeDesc'

const Option = Select.Option;

class ComputeModeAdd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: [],
      detail: {},
      dataType: null
    };
    this.actionType = 'add';
    this.form = null;
    this.api = 'computeMode';
  }

  componentWillMount() {
    this.actionType = this.props.actionType;
    if (this.props.actionType) {
      if (this.actionType === 'update') {
        this.calculate_type_id = this.props.record.calculate_type_id;
      }
    }
    if (this.props.record && this.props.record.output_data_type) {
      this.setState({ dataType: this.props.record.output_data_type })
    }
  }

  handleSubmit = () => {
    this.form.validateFields((err, values) => {
      if (!err) {
        const params = {
          calculate_type_name: values.calculate_type_name,
          calculate_type_code: values.calculate_type_code,
          calculate_field_type: values.calculate_field_type.join(),
          remark: values.remark,
          output_data_type: values.output_data_type,
          groovy_content: values.groovy_content
        };
        if (this.actionType === 'update') {
          params.calculate_type_id = this.calculate_type_id;
        }
        services[this.api][this.actionType](params).then(data => {
          if (data.code === 0) {
            message.success(data.msg);
            if (this.props.closeModal) {
              this.props.closeModal();
            }
          } else {
            message.error(data.msg);
          }
        });
      }
    });
  };

  handleConfirmBlur = e => {
    const { value } = e.target;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };

  handleChangeDesc = (code) => {
    this.setState({ dataType: code })
  }

  render() {
    const { calculate_type_name, calculate_type_code, calculate_field_type, remark, output_data_type, groovy_content } =
      this.props.record || {};

    const formItems = [
      {
        label: {
          label: '计算方式名称',
          className: 'tantuer-form-item'
        },
        name: 'calculate_type_name',
        options: {
          initialValue: calculate_type_name,
          rules: [
            { required: true, message: '请填写计算方式名称' },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' }
          ]
        },
        component: <Input placeholder='请填写' disabled={this.actionType === 'detail'} />
      },
      {
        label: {
          label: 'Code',
          className: 'tantuer-form-item2  tantuer-form-item-nowrap'
        },
        name: 'calculate_type_code',
        options: {
          initialValue: calculate_type_code,
          rules: [
            { required: true, message: '请填写计算方式Code' },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[a-zA-Z][_a-zA-Z0-9]*$/, message: '限英文数字下划线，并以英文开头' }
          ]
        },
        component: (
          <Input
            placeholder='仅支持英文数字下划线,且必须以英文开头，添加后无法修改'
            disabled={this.actionType === 'update' || this.actionType === 'detail'}
          />
        )
      },
      {
        label: {
          label: '计算字段数据类型',
          className: 'tantuer-form-item'
        },
        name: 'calculate_field_type',
        options: {
          initialValue: calculate_field_type,
          rules: [{ required: true, message: '请选择' }]
        },
        // component: <Input placeholder='请选择' />
        component: (
          <Select mode='multiple' placeholder='请选择' allowClear showArrow={true} disabled={this.actionType === 'detail'}>
            {this.props.data_types.map((item, index) => {
              return (
                <Option value={item.code} key={item.code}>
                  {item.value}
                </Option>
              );
            })}
          </Select>
        )
      },
      {
        label: {
          label: '描述',
          className: 'tantuer-form-item2  tantuer-form-item-nowrap'
        },
        name: 'remark',
        options: {
          initialValue: remark,
          rules: [
            { max: 256, message: '最长256个字符' }
          ]
        },
        component: <Input placeholder='请填写' disabled={this.actionType === 'detail'} />
      },
      {
        label: {
          label: '输出数据类型',
          className: 'tantuer-form-item',
        },
        name: 'output_data_type',
        options: {
          initialValue: output_data_type,
          rules: [{ required: true, message: '请选择' }],
        },
        component: (
          <Select
            style={{ width: '95%' }}
            placeholder='请选择'
            disabled={this.actionType === 'detail'}
            onChange={this.handleChangeDesc}
          >
            {this.props.data_types.map((it) => {
              return (
                <Select.Option value={it.code} key={it.code}>
                  {it.value}
                </Select.Option>
              );
            })}
          </Select>
        ),
        after: <DataTypeDesc dataType={this.state.dataType}></DataTypeDesc>
      },
      {
        label: {
          label: '脚本',
          className: 'tantuer-form-item  tantuer-form-item-nowrap'
        },
        name: 'groovy_content',
        span: 24,
        options: {
          initialValue: groovy_content,
          rules: [{ required: true, message: '请填写脚本' }]
        },
        component: (
          <ScriptEditor
            // onChange={onChange}
            disabled={this.actionType === 'detail'}
            placeholder={
              '1.获取字段的值\n在Groovy中获取指定字段的值，可以以"ctx.字段code"的方式获取，例如 获取code为 int_b的字段值"ctx.int_b"\n2.特殊类型的字段类型转换\n获取int_b的 int值：Integer.valueOf(ctx.int_b)\n3.表达式\n简单版：ctx.aaa == null && ctx.bbb !== null\n复杂版：Integer.valueOf(ctx.int_b) == 0 && Double.valueOf(ctx.int_c) > 5'
            }
          />
        )
      }
    ];

    return (
      <CustomForm
        {...this.props}
        closeModal={this.props.closeModal}
        createForm={ref => (this.form = ref)}
        formItems={formItems}
        onHandleSubmit={this.handleSubmit}
        hideSubmit={this.actionType === 'detail'}
      />
    );
  }
}

function mapStateToProps(state) {
  return {
    field_classification: state.code.field_classification,
    data_types: state.code.data_type || []
  };
}
export default connect(mapStateToProps)(ComputeModeAdd);
